<!--
 * @Autor: Ruohong Yu
 * @Date: 2022-09-14 11:16:49
 * @Description: file content
 * @FilePath: \ebook\src\components\shelf\ShelfTitle.vue
-->
<template>
  <transition name="fade">
    <div class="shelf-title" :class="{'hide-shadow':ifHideShadow}" v-show="shelfTitleVisible">
      <div class="shelf-title-text-wrapper">
        <span class="shelf-title-text">{{title}}</span>
        <span class="shelf-title-sub-text" v-show="isEditMode">{{selectedText}}</span>
      </div>
      <div class="shelf-title-btn-wrapper shelf-title-left" v-if="showClear">
        <span class="shelf-title-btn-text" @click="clearCache">{{$t('shelf.clearCache')}}</span>
      </div>
      <div class="shelf-title-btn-wrapper shelf-title-left" v-if="showBack">
        <span class="icon-back" @click="back"></span>
      </div>
      <div class="shelf-title-btn-wrapper" :class="{'shelf-title-left':changeGroupLeft,'shelf-title-right':changeGroupRight}" @click="changeGroup" v-if="showChangeGroup">
        <span class="shelf-title-btn-text">{{$t('shelf.editGroup')}}</span>
      </div>

      <div class="shelf-title-right">
        <div class="hands" v-if="isSuspendBallVisible" @click="changeHand">
        </div>
        <div class="no-hands" v-if="!isSuspendBallVisible" @click="changeHand">
        </div>
        <div class="shelf-title-btn-edit" v-if="showEdit">
          <span class="shelf-title-btn-text" @click="onEditClick">{{isEditMode?$t('shelf.cancel'):$t('shelf.edit')}}</span>
        </div>
        <div class="login" @click="onUserClick" v-if="isLogin">
          <img class="circleImg" :src="imgsrc"/>
        </div>
        <div class="login" v-else>
          <span class="shelf-title-btn-text" @click="onUserClick">{{isLogin?$t('shelf.welcome').replace('$1',userName):$t('shelf.needLogin')}}</span>
        </div>
      </div>
    </div>
  </transition>
  <div class="camera_outer">
    <video id="videoCamera" :width="videoWidth" :height="videoHeight" autoplay></video>
    <canvas style="display:none;" id="canvasCamera" :width="videoWidth" :height="videoHeight" ></canvas>
  </div>
  <toast :text="toastText" ref="toast"></toast>
  <popup :title="popupTitle" :btn="popupBtn" ref="popup"></popup>
  <shelf-group-dialog :showNewGroup="showGroupDialog" :groupName="groupName" ref="groupDialog"></shelf-group-dialog>
  <tipsmark v-if="isfirst"></tipsmark>
</template>

<script>
import { closeHandControl } from '../../api/store'
import { clearLocalStorage, getAvatar, getUsername, saveBookShelf } from '@/utils/localStorage'
import { storeShelfMixin } from '../../utils/mixin'
import { clearLocalForage } from '@/utils/localForage'
import Toast from '../common/Toast.vue'
import Popup from '../common/Popup.vue'
import Tipsmark from '../common/Tipsmark.vue'
import ShelfGroupDialog from './ShelfGroupDialog.vue'
import { appendAddToShelf, computeId, removeAddFromShelf } from '@/utils/store'
import { changeShelfGroup } from '@/api/shelf'
export default {
  mixins: [storeShelfMixin],
  props: {
    title: String
  },
  components: { Toast, Popup, ShelfGroupDialog, Tipsmark },
  computed: {
    isfirst () {
      return this.isFirst
    },
    isSuspendBallVisible () {
      return this.suspendBallVisible
    },
    emptyCategory () {
      return !this.shelfCategory || !this.shelfCategory.itemList || this.shelfCategory.itemList.length === 0
    },
    showEdit () {
      return this.currentType === 1 || !this.emptyCategory
    },
    showClear () {
      return this.currentType === 1
    },
    showBack () {
      return this.currentType === 2 && !this.isEditMode
    },
    showChangeGroup () {
      return this.currentType === 2 && (this.isEditMode || this.emptyCategory)
    },
    changeGroupLeft () {
      return !this.emptyCategory
    },
    changeGroupRight () {
      return this.emptyCategory
    },
    selectedText () {
      const selectedNumber = this.shelfSelected ? this.shelfSelected.length : 0
      return selectedNumber <= 0 ? this.$t('shelf.selectBook') : (selectedNumber === 1 ? this.$t('shelf.haveSelectedBook').replace('$1', selectedNumber) : this.$t('shelf.haveSelectedBooks').replace('$1', selectedNumber))
    }
  },
  watch: {
    offsetY (offsetY) {
      if (offsetY > 0) {
        this.ifHideShadow = false
      } else {
        this.ifHideShadow = true
      }
    },
    isSuspendBallVisible (data) {
      if (data) {
        if (this.isFirst === undefined || this.isFirst === null) {
          this.setIsFirst(true)
        } else {
          this.toastText = this.$t('shelf.setHandSuccess')
          this.$refs.toast.updateText(this.toastText)
          this.$refs.toast.show()
        }
        this.$socket.emit('handidentify', 'need open camera')
      } else {
        closeHandControl().then((res) => {
          console.log(res.data)
          this.toastText = this.$t('shelf.closeHandSuccess')
          this.$refs.toast.updateText(this.toastText)
          this.$refs.toast.show()
        })
      }
    }
  },
  mounted () {
    this.$socket.connect() // 创建socket连接
    console.log('连接中')
    this.userName = getUsername()
    this.isLogin = this.userName === undefined ? false : this.userName === null ? false : this.userName !== ''
    const img = getAvatar()
    this.imgsrc = img === undefined ? require('../../assets/images/loginbg.png') : img === null ? require('../../assets/images/loginbg.png') : img
  },
  sockets: {
    connect () {
      console.log('链接成功')
    },
    disconnect () {
      console.log('断开链接')
    },
    reconnect () {
      console.log('重新链接')
    }
  },
  data () {
    return {
      isHanding: false,
      ifHideShadow: true,
      toastText: '',
      dialogTitle: '',
      popupTitle: '',
      popupBtn: [],
      showGroupDialog: false,
      groupName: '',
      videoWidth: 800,
      videoHeight: 300,
      thisCancas: null,
      thisContext: null,
      thisVideo: null,
      ws: null,
      isLogin: false,
      userName: '',
      imgsrc: null
    }
  },
  methods: {
    onUserClick () {
      if (this.isLogin) {
        this.$router.push({
          path: '/userinfo'
        })
      } else {
        clearLocalStorage()
        clearLocalForage()
        this.$router.push({
          path: '/login'
        })
      }
    },
    getCompetence () {
      const _this = this
      this.thisCancas = document.getElementById('canvasCamera')
      this.thisContext = this.thisCancas.getContext('2d')
      this.thisVideo = document.getElementById('videoCamera')
      // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {}
      }
      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
      // 使用getUserMedia，因为它会覆盖现有的属性。
      // 这里，如果缺少getUserMedia属性，就添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          const getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia
          // 有些浏览器不支持，会返回错误信息
          // 保持接口一致
          if (!getUserMedia) {
            return Promise.reject(new Error('getUserMedia is not implemented in this browser'))
          }
          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject)
          })
        }
      }
      const constraints = { audio: false, video: { width: this.videoWidth, height: this.videoHeight, transform: 'scaleX(-1)' } }
      navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
        // 旧的浏览器可能没有srcObject
        if ('srcObject' in _this.thisVideo) {
          _this.thisVideo.srcObject = stream
        } else {
          // 避免在新的浏览器中使用它，因为它正在被弃用。
          _this.thisVideo.src = window.URL.createObjectURL(stream)
        }

        _this.thisVideo.onloadedmetadata = function (e) {
          _this.thisVideo.play()
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // base64转文件
    dataURLtoFile (dataurl, filename) {
      const arr = dataurl.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename, { type: mime })
    },
    // 关闭摄像头
    stopNavigator () {
      this.thisVideo.srcObject.getTracks()[0].stop()
    },
    changeHand () {
      this.setSuspendBallVisible(!this.suspendBallVisible)
    },
    onComplete () {
      this.hidePopup()
      this.setShelfList(this.shelfList.filter(book => book.id !== this.shelfCategory.id)).then(() => {
        saveBookShelf(this.shelfList)
        this.$router.go(-1)
        this.setIsEditMode(false)
      })
    },
    deleteGroup () {
      if (!this.emptyCategory) {
        changeShelfGroup('0', getUsername(), this.shelfCategory.itemList).then((res) => {
          if (res.data.status === 0) {
            this.setShelfSelected(this.shelfCategory.itemList)
            this.setShelfList(this.shelfList.map(book => {
              if (book.type === 2 && book.itemList) {
                book.itemList = book.itemList.filter(subBook => !subBook.selected)
              }
              return book
            })).then(() => {
              const list = computeId(appendAddToShelf([].concat(removeAddFromShelf(this.shelfList), ...this.shelfSelected)))
              this.setShelfList(list).then(() => {
                this.toastText = this.$t('shelf.moveBookOutSuccess')
                this.$refs.toast.show()
                this.$refs.toast.updateText(this.toastText)
                this.onComplete()
              })
            })
          }
        })
      } else {
        this.onComplete()
      }
    },
    showDeleteGroup () {
      this.hidePopup()
      setTimeout(() => {
        this.popupTitle = this.$t('shelf.deleteGroupTitle')
        this.popupBtn = [
          {
            text: this.$t('shelf.confirm'),
            type: 'danger',
            click: () => {
              this.deleteGroup()
            }
          },
          {
            text: this.$t('shelf.cancel'),
            click: () => {
              this.hidePopup()
            }
          }
        ]
        this.$refs.popup.show()
      }, 200)
    },
    changeGroupName () {
      this.hidePopup()
      this.showGroupDialog = true
      this.groupName = this.shelfCategory.title
      this.$refs.groupDialog.show()
    },
    hidePopup () {
      this.$refs.popup.hide()
    },
    changeGroup () {
      this.popupBtn = [
        {
          text: this.$t('shelf.editGroupName'),
          click: () => {
            this.changeGroupName()
          }
        },
        {
          text: this.$t('shelf.deleteGroup'),
          type: 'danger',
          click: () => {
            this.showDeleteGroup()
          }
        },
        {
          text: this.$t('shelf.cancel'),
          click: () => {
            this.hidePopup()
          }
        }
      ]
      this.$refs.popup.show()
    },
    back () {
      this.$router.go(-1)
      this.setIsEditMode(false)
    },
    onEditClick () {
      if (!this.isEditMode) {
        this.setShelfSelected([])
        this.shelfList.forEach(item => {
          item.selected = false
          if (item.itemList) {
            item.itemList.forEach(subItem => {
              subItem.selected = false
            })
          }
        })
      }
      this.setIsEditMode(!this.isEditMode)
    },
    clearCache () {
      // clearLocalStorage()
      clearLocalForage()
      // this.setShelfList([])
      // this.setShelfSelected([])
      // this.getShelfList()
      this.toastText = this.$t('shelf.clearCacheSuccess')
      this.$refs.toast.show()
      this.$refs.toast.updateText(this.toastText)
    }
  }
}
</script>

<style lang="scss" scoped>
  .shelf-title{
    z-index: 130;
    position: relative;
    width: 100%;
    height: px2rem(42);
    background: white;
    box-shadow: 0 px2rem(2) px2rem(2) 0 rgba(0,0,0,.1);
    &.hide-shadow{
      box-shadow: none;
    }
    .shelf-title-text-wrapper{
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: px2rem(42);
      @include columnCenter;
      .shelf-title-text{
        font-weight: 100;
        font-size: px2rem(16);
        line-height: px2rem(20);
        font-weight: bold;
        color: #666;
      }
      .shelf-title-sub-text{
        font-size: px2rem(10);
        color: #666;
      }
    }
    @media screen and (max-width: 767px) {
      .shelf-title-text-wrapper{
        display: none;
      }
    }
    .shelf-title-right{
      display: flex;
      position: absolute;
      right: px2rem(10);
      height: 100%;
      cursor: pointer;
      font-size: px2rem(14);
      color: #666;
      @include right;
      .login{
        padding: 0 px2rem(10) 0 px2rem(10);
        color: rgb(161, 0, 0);
        &:hover{
          transform: scale(1.1);
        }
        .circleImg{
          border-radius: 50%;
          width:px2rem(30);
          height:px2rem(30);
        }
      }
      .logout{
        font-size: px2rem(12);
        &:hover{
          transform: scale(1.1);
        }
      }
      .hands{
        width:px2rem(35);
        height:px2rem(30);
        background:url('../../assets/images/hands1.png') no-repeat center;
        background-size:contain;
        line-height: px2rem(30);
        &:hover{
          transform: scale(1.1);
        }
      }
      .no-hands{
        width:px2rem(35);
        height:px2rem(30);
        background:url('../../assets/images/no-hands1.png') no-repeat center;
        background-size:contain;
        &:hover{
          transform: scale(1.1);
        }
      }
      .shelf-title-btn-edit{
        padding: 0 px2rem(2);
        @include center;
        &:hover{
          transform: scale(1.1);
        }
      }
    }
    .shelf-title-btn-wrapper{
      position: absolute;
      top: 0;
      box-sizing: border-box;
      height: 100%;
      cursor: pointer;
      @include center;
      .shelf-title-btn-text{
        font-size: px2rem(14);
        color: #666;
      }
      .icon-back{
        font-size: px2rem(20);
        color: #666;
      }
      &.shelf-title-left{
        left: 0;
        padding-left: px2rem(15);
      }
      &:hover{
        transform: scale(1.1);
      }
    }
  }
</style>
